package com.lanbu.system.service.impl;

import com.lanbu.system.domain.mongo.MongoUsers;
import com.lanbu.system.mapper.MongoUsersRepository;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class MongoUsersService {

    @Autowired
    private MongoUsersRepository mongoUsersRepository;

    public MongoUsers updateUser(ObjectId id, MongoUsers userDetails) {
        Optional<MongoUsers> existingUser = mongoUsersRepository.findById(id);
        if (existingUser.isPresent()) {
            MongoUsers user = existingUser.get();
            // 更新用户的各个字段
            user.setStatus(userDetails.getStatus());
            user.setUsername(userDetails.getUsername());
            user.setPassword(userDetails.getPassword());
            user.setAvatar(userDetails.getAvatar());
            user.setPromotionRate(userDetails.getPromotionRate());
            user.setTimezone(userDetails.getTimezone());
            user.setCreateTime(userDetails.getCreateTime());
            user.setVersion(userDetails.getVersion());

            // 保存更新后的用户
            return mongoUsersRepository.save(user);
        } else {
            // 如果用户不存在，可以抛出一个自定义异常
            throw new RuntimeException("User not found with id: " + id);
        }
    }

    public List<MongoUsers> findAll() {
        return mongoUsersRepository.findAll();
    }

    public Optional<MongoUsers> findById(ObjectId id) {
        return mongoUsersRepository.findById(id);
    }

    public MongoUsers findByUsername(String username) {
        return mongoUsersRepository.findByUsername(username);
    }

    public MongoUsers save(MongoUsers user) {
        return mongoUsersRepository.save(user);
    }

    public void deleteById(ObjectId id) {
        mongoUsersRepository.deleteById(id);
    }
}
